package com.ruoyi.web.core.function;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.web.core.anno.FunctionName;
import org.beetl.core.Context;
import org.beetl.core.Function;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 字典函数
 * @author iterking
 **/
@FunctionName("dict")
@Component
public class DictFunction implements Function {

    @Autowired
    private ISysDictDataService dictDataService;

    @Override
    public Object call(Object[] paras, Context ctx) {
        Object dictType = paras[0];
        if (dictType != null){
            try{

                if(paras.length > 1){
                    Object dictValue = paras[1];
                    String label = dictDataService.selectDictLabel(dictType.toString(), dictValue.toString());
                    if(StrUtil.isNotEmpty(label)){
                        ctx.byteWriter.write(label.getBytes("UTF-8"));
                    }
                }else{
                    List<SysDictData> sysDictData = dictDataService.selectDictDataByType(dictType.toString());
                    ctx.byteWriter.write(JSONUtil.toJsonStr(sysDictData).getBytes("UTF-8"));
                }
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
        return "";
    }
}
